package handlers

import (
	"encoding/json"
	"post-mngr/cache"
	"post-mngr/model"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	desc := c.PostForm("desc")
	author := c.PostForm("author")
	if title == "" || desc == "" || author == "" {
		c.JSON(200, gin.H{
			"message": "字段不可为空",
			"code":    500,
		})
		return
	}

	data := model.Article{
		Title:  title,
		Desc:   desc,
		Author: author,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"message": "数据添加失败",
			"code":    500,
		})
		return
	}

	c.JSON(200, gin.H{
		"message": "add",
		"code":    200,
	})
	return

}

func Del(c *gin.Context) {
	id := c.PostForm("id")
	err := model.DB.Debug().Where("id=?", id).Delete(&model.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"message": "删除失败",
			"code":    500,
		})
		return
	}

	c.JSON(200, gin.H{
		"message": "删除成功",
		"code":    200,
	})
	return
}

func List(c *gin.Context) {
	var article []model.Article
	//设置redis的key
	redis_list_ley := "list_article"
	resulit, _ := cache.Rdb.Get(cache.Ctx, redis_list_ley).Result()
	if resulit == "" {
		//从mysql数据
		model.DB.Debug().Find(&article)
		//设置到缓存redis
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_list_ley, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(resulit), &article)
	}

	c.JSON(200, gin.H{
		"message": "成功",
		"code":    200,
		"data":    article,
	})
	return

}
